package com.icesoft.system.controller;

import com.icesoft.framework.core.controller.BaseCrudRestController;
import com.icesoft.framework.core.vo.JsonResult;
import com.icesoft.system.auth.entity.LoginUser;
import com.icesoft.system.entity.Permission;
import com.icesoft.system.entity.User;
import com.icesoft.system.permission.annotation.BindPermission;
import com.icesoft.system.permission.cache.PermissionCacheManager;
import com.icesoft.system.permission.entity.ApiPermission;
import com.icesoft.system.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequiredArgsConstructor
@BindPermission(name = "权限管理")
@RequestMapping("/system/permission")
public class PermissionController extends BaseCrudRestController<Permission> {

	@GetMapping("getPermission")
	public JsonResult<?> getPermission() {
		LoginUser<User> loginUser = SecurityUtils.getLoginUser();
		Set<String> authorities = loginUser.getPermissions();

		List<ApiPermission> apiPermissions = new ArrayList<>();
		List<ApiPermission> apiPermissionVoList = PermissionCacheManager.extractAllApiPermissions();
		apiPermissionVoList.forEach(apiPermission -> {
			if (!apiPermission.isDevelop()) {
				List<ApiPermission> children = new ArrayList<>();
				apiPermission.getApiPermissionList().forEach(item -> {
					if (!item.isDevelop()) {
						children.add(item);
					}
				});
				apiPermission.setApiPermissionList(children);
				apiPermissions.add(apiPermission);
			}
		});

		if (!SecurityUtils.isAdmin()) {
			List<ApiPermission> userApiPermissions = new ArrayList<>();
			apiPermissions.forEach(apiPermission -> {
				if (authorities.stream().anyMatch(url -> {
					AntPathMatcher antPathMatcher = new AntPathMatcher();
					return antPathMatcher.match(apiPermission.getUri(), url);
				})) {
					List<ApiPermission> children = new ArrayList<>();
					apiPermission.getApiPermissionList().forEach(item -> {
						if (!item.isDevelop()) {
							children.add(item);
						}
					});
					apiPermission.setApiPermissionList(children);
					userApiPermissions.add(apiPermission);
				}
			});
			return JsonResult.OK(userApiPermissions);
		}

		return JsonResult.OK(apiPermissions);
	}
}
